﻿using System.Web.Mvc;
using System.Web.Mvc.Filters;
using System.Web.Security;
using zqdn.Web.App_Start;

namespace zqdn.Web.Filters
{
    public class NormalAuthFilter : ActionFilterAttribute, IAuthenticationFilter
    {
        public int _role;

        public NormalAuthFilter()
            : this(0)
        {
        }

        public NormalAuthFilter(int role)
        {
            this._role = role;
        }

        public void OnAuthentication(AuthenticationContext filterContext)
        {
            bool skipAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true)
                                        || filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), inherit: true);
            if (skipAuthorization) return;

            //若用户未登陆，则报未验证错误。前端ajax请求和FormAuth会处理此异常
            if (!SessionContext.IsAuthenticated)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    //filterContext.HttpContext.Response.StatusCode = 401;
                    //filterContext.HttpContext.Response.End();
                    var _url = (this._role != 0 ? "/user/login/" : "/admin/user/login");
                    var result = new JsonResult { Data = new { Result = "err", Msg = "请先登录!", Url = _url } };

                    filterContext.Result = result;
                }
                else
                {
                    var _url = (this._role != 0 ? "/user/login/" : "/admin/user/login");
                    filterContext.Result = new RedirectResult(_url);
                    //filterContext.Result = new HttpUnauthorizedResult();
                }
                return;
            }

            // 已经登陆用户、角色不为空, 需要判断角色是否匹配


            if (this._role != 0)
            {
                if (SessionContext.CurrentUser.Role != 0 && (SessionContext.CurrentUser.Role == _role || _role == 5))
                    return;

                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var result = new JsonResult { Data = new { Result = "err", msg = "您没有权限进行此项操作!" } };
                    filterContext.Result = result;
                }
                else
                {
                    //var result = new ContentResult { Content = "您没有权限进行此项操作!" };
                    //filterContext.Result = result;

                    filterContext.Result = new RedirectResult("/home/error");
                }
            }

           

        }
        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
        }

    }
}



